<?php
	
	require_once(EAV_MODELS_PATH.'abstract_fieldset.php');

	class Fieldset extends AbstractFieldset
	{
		var $name = "Fieldset";
		protected $fieldModelName = "CustomField"; 
		const TYPE_REVIEW = "Review";
		const TYPE_LISTING = "Listing";
		function initialize()
		{
			$this->setFieldProperties('label',array('type'=>"text",'group'=>array('add','grid'), 'label'=>'Label'));
			$this->setFieldProperties('show_label',array('type'=>"radio",'options'=>array('1'=>'yes','0'=>'No'),'group'=>array('add','grid'), 'label' => 'Do you want to display the title of this field group on website ?','default'=>1));
			$this->setFieldProperties('entity',array('type'=>"select",'options'=>$this->getOptionEntities(),'group'=>array('add','grid'), 'label' => 'Type'));
						
			parent::initialize();	
		}
		
		function getOptionEntities()
		{
			return array(self::TYPE_REVIEW =>__("Review"),self::TYPE_LISTING =>__("Listing"));
		}
		
		function getOptionList()
		{
			$fieldseData = $this->find('all',array('recursive'=>-1));
			$fieldsets = array();
			if(!empty($fieldseData))
			{
				foreach($fieldseData as $fieldset)
				{
					$fieldsets[$fieldset[$this->alias]['id']] = __($fieldset[$this->alias]['entity']).': '.__($fieldset[$this->alias]['name']);
				}
			}
			return $fieldsets;
		}
		
		function afterSave($created)
		{
			$this->refreshCustomFieldsCache($this->id);
			return parent::afterSave($created);
		}
		
		function refreshCustomFieldsCache($id)
		{
			$listingTypeIds =  cri('ListingTypeFieldset')->find("list",array("conditions"=>array('fieldset_id'=>$id),'fields'=>array('listing_type_id')));
			foreach($listingTypeIds as $listingTypeId)
			{
				cri('ListingType')->refreshCustomFieldsCache($listingTypeId);
			}
		}
			
		function afterDelete()
		{
			$this->CustomField->deleteAll(array('CustomField.fieldset_id'=>$this->id));
			parent::afterDelete();
		}
		//@GEO MAP INTERACTION
		function getFieldsetFieldProperties($id)
		{
			$fieldProperties = parent::getFieldsetFieldProperties($id);
			$fieldIdMap = $this->getFieldModel()->find('list',array('recursive'=>-1,'conditions'=>array($this->foreignKey => $id),'fields'=>array("name","id")));
			foreach($fieldProperties as $fieldName => $property)
			{
				if(isset($fieldIdMap[$fieldName]))
				{
					$property['custom_field_id'] = $fieldIdMap[$fieldName];
				}else
				{
					$property['custom_field_id'] = null;
				}
				$fieldProperties[$fieldName] = $property;
			}
			$mapFields = cri("MapConfig")->getMapingFields();
			foreach($mapFields as $mapField)
			{
				$configField = cr("MapConfig.$mapField");
				if($configField && isset($fieldProperties[$configField]))
				{
					$fieldProperties[$configField]['map_'.$mapField] = true;
				}
			}
			return $fieldProperties;
		}
	}
	
	
?>